package com.test.aspectdemo

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.JavascriptInterface
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"

    private val REQUEST_CODE_STORAGE_PERMISSION: Int = 1000

    var pubString = "类中成员变量"

    override fun onCreate(savedInstanceState: Bundle?) {
        Log.d(TAG, "onCreate: ")
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<View>(R.id.copy_clipboard2txt).setOnClickListener {
            TxtUtil.test()
        }

    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onStart: ")

        handlePermission()
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume: ")

        // test()
        // testInt(1)
        testString("1", "22", "333")
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "onPause: ")
    }

    @JavascriptInterface
    fun test() {
        Log.d(TAG, "test: ")
    }


    @JavascriptInterface
    fun testInt(i: Int) {
        Log.d(TAG, "testInt: 实参=$i")
    }

    @JavascriptInterface
    fun testString(s1: String, s2: String, s3: String) {
        Log.d(TAG, "testString: 实参=$s1 $s2 $s3")
    }


    /**
     * todo 即便没存储管理权限，申请该权限也不会弹框
     * todo 申请权限，不论是否弹框，都会导致Activity走onPause和onResume
     */
    private fun handlePermission() {
        // 判断是否有存储权限
        var writePermission = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED
        // 判断是否有存储管理权限
        var managePermission = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.MANAGE_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED
        Log.d(TAG, "onStart: writePermission=$writePermission managePermission=$managePermission")
        // if (!(writePermission && managePermission)) {
        if (!writePermission) {
            // 申请权限，不论是否弹框，都会导致Activity走onPause和onResume
            ActivityCompat.requestPermissions(
                this,
                arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                    // Manifest.permission.MANAGE_EXTERNAL_STORAGE
                )
                ,
                REQUEST_CODE_STORAGE_PERMISSION
            )
        }
    }
}